import { useState, useEffect, useCallback } from 'react';
import { invoke } from '@tauri-apps/api/core';

// API 状态类型
export interface ApiState<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

// API 选项
export interface ApiOptions {
  immediate?: boolean;
  onSuccess?: (data: any) => void;
  onError?: (error: string) => void;
}

// 通用 API Hook
export function useApi<T = any>(
  command: string,
  args?: any,
  options: ApiOptions = {}
) {
  const { immediate = true, onSuccess, onError } = options;

  const [state, setState] = useState<ApiState<T>>({
    data: null,
    loading: false,
    error: null,
  });

  const execute = useCallback(
    async (executeArgs?: any) => {
      setState(prev => ({ ...prev, loading: true, error: null }));

      try {
        const result = await invoke<T>(command, executeArgs || args);
        setState({ data: result, loading: false, error: null });
        onSuccess?.(result);
        return result;
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        setState({ data: null, loading: false, error: errorMessage });
        onError?.(errorMessage);
        throw error;
      }
    },
    [command, args, onSuccess, onError]
  );

  const reset = useCallback(() => {
    setState({ data: null, loading: false, error: null });
  }, []);

  useEffect(() => {
    if (immediate) {
      execute();
    }
  }, [execute, immediate]);

  return {
    ...state,
    execute,
    reset,
  };
}

// 应用信息 Hook
export function useAppInfo() {
  return useApi('get_app_info');
}

// 系统信息 Hook
export function useSystemInfo() {
  return useApi('get_system_info');
}

// 配置管理 Hook
export function useAppConfig() {
  const [config, setConfig] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchConfig = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await invoke('get_app_config');
      setConfig(result as any);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, []);

  const updateConfig = useCallback(async (newConfig: any) => {
    setLoading(true);
    setError(null);
    try {
      await invoke('set_app_config', { config: newConfig });
      setConfig(newConfig);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchConfig();
  }, [fetchConfig]);

  return {
    config,
    loading,
    error,
    updateConfig,
    refetch: fetchConfig,
  };
}

// 日志管理 Hook
export function useLogs() {
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchLogs = useCallback(async (limit?: number, level?: string) => {
    setLoading(true);
    setError(null);
    try {
      const result = await invoke('get_logs', { limit, level });
      setLogs(result as any[]);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, []);

  const clearLogs = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      await invoke('clear_logs');
      setLogs([]);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    logs,
    loading,
    error,
    fetchLogs,
    clearLogs,
  };
}

// 文件操作 Hook
export function useFileOperations() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const readFile = useCallback(async (path: string) => {
    setLoading(true);
    setError(null);
    try {
      const content = await invoke<string>('read_text_file', { path });
      return content;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const writeFile = useCallback(async (path: string, content: string) => {
    setLoading(true);
    setError(null);
    try {
      await invoke('write_text_file', { path, content });
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const fileExists = useCallback(async (path: string) => {
    try {
      return await invoke<boolean>('file_exists', { path });
    } catch (err) {
      return false;
    }
  }, []);

  const createDirectory = useCallback(async (path: string) => {
    setLoading(true);
    setError(null);
    try {
      await invoke('create_directory', { path });
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    loading,
    error,
    readFile,
    writeFile,
    fileExists,
    createDirectory,
  };
}

// 窗口管理 Hook
export function useWindowManager() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const toggleVisibility = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      await invoke('toggle_window_visibility');
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, []);

  const centerWindow = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      await invoke('center_window');
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, []);

  return {
    loading,
    error,
    toggleVisibility,
    centerWindow,
  };
}

// 工具函数 Hook
export function useUtils() {
  const generateUuid = useCallback(async () => {
    return await invoke<string>('generate_uuid');
  }, []);

  const getCurrentTimestamp = useCallback(async () => {
    return await invoke<string>('get_current_timestamp');
  }, []);

  const getProcessInfo = useCallback(async () => {
    return await invoke('get_process_info');
  }, []);

  return {
    generateUuid,
    getCurrentTimestamp,
    getProcessInfo,
  };
}

// 缓存 Hook
export function useCache<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl = 5 * 60 * 1000
) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(
    async (force = false) => {
      const cacheKey = `cache_${key}`;
      const timestampKey = `cache_${key}_timestamp`;

      if (!force) {
        const cached = localStorage.getItem(cacheKey);
        const timestamp = localStorage.getItem(timestampKey);

        if (cached && timestamp) {
          const age = Date.now() - parseInt(timestamp);
          if (age < ttl) {
            try {
              const parsedData = JSON.parse(cached);
              setData(parsedData);
              return parsedData;
            } catch {
              // 缓存数据无效，继续获取新数据
            }
          }
        }
      }

      setLoading(true);
      setError(null);

      try {
        const result = await fetcher();
        setData(result);

        // 缓存数据
        localStorage.setItem(cacheKey, JSON.stringify(result));
        localStorage.setItem(timestampKey, Date.now().toString());

        return result;
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : String(err);
        setError(errorMessage);
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [key, fetcher, ttl]
  );

  const clearCache = useCallback(() => {
    localStorage.removeItem(`cache_${key}`);
    localStorage.removeItem(`cache_${key}_timestamp`);
    setData(null);
  }, [key]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return {
    data,
    loading,
    error,
    refetch: () => fetchData(true),
    clearCache,
  };
}
